import requests
import json
import math

def calculate_distance(lat1, lon1, lat2, lon2):
    # 将经纬度转换为弧度
    lat1 = math.radians(lat1)
    lon1 = math.radians(lon1)
    lat2 = math.radians(float(lat2))
    lon2 = math.radians(float(lon2))

    # 使用Haversine公式计算距离
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    radius = 6371  # 地球半径（单位：公里）
    distance = radius * c

    return distance
def cleanAddress():

    # 读取地址文件
    with open('addresses.txt', 'r', encoding='utf-8') as file:
        addresses = file.readlines()

    with open("addressPositions.json", "r", encoding='utf-8') as file:
        json_data = file.read()
    # 将 JSON 数据反序列化为变量
    positionMap = json.loads(json_data)
    # 发送请求获取地址的坐标
    address_positions = []

    #for address in positionMap:
    for address in addresses:
        address = address.strip()  # 去除换行符
        if address in positionMap:
            continue
            # if positionMap[address].get('tag') is not None:
            #     continue
            # #更新tag
            # try:
            #     url = f'https://api.map.baidu.com/place/v2/search?query={address}&output=json&scope=2&location=30.240291,120.311736&radius=30000&ak=EDbe70ea2390c3777961b218f0e2db6e'
            #     response = requests.get(url)
            #     data = response.json()
            #     if data['status'] == 302:
            #         break
            #     if data['status'] != 0:
            #         print(address)
            #         continue
            #     results = data['results']
            #     if len(results) <=0:
            #         print(address)
            #         continue
            #     positionMap[address]['tag']=results[0]["detail_info"]["tag"]
            #     print(positionMap[address]['tag'])
            # finally:
            #     continue

            # distance = calculate_distance(30.240291,120.311736, positionMap[address]['lat'], positionMap[address]['lng'])
            # if distance < 20:
            #     continue
            # print(address +"  距离为：", distance, "公里")

        # url = f'https://api.map.baidu.com/geocoding/v3/?address={address}&output=json&city=杭州市&location=30.240291,120.311736&ak=EDbe70ea2390c3777961b218f0e2db6e'


        url = f'https://api.map.baidu.com/place/v2/search?query={address}&output=json&scope=2&location=30.240291,120.311736&radius=30000&ak=EDbe70ea2390c3777961b218f0e2db6e'
        response = requests.get(url)
        data = response.json()
        if data['status'] == 302:
            break
        if data['status'] != 0:
            print(address)
            continue
        results = data['results']
        if len(results) <=0:
            print(address)
            continue
        location = results[0]['location']
        latitude = location['lat']
        longitude = location['lng']
        formatted_latitude = "{:.6f}".format(latitude)
        formatted_longitude = "{:.6f}".format(longitude)
        position = f'{formatted_longitude,{formatted_latitude},{address}}'
        address_positions.append(position)
        positionMap[address] = {
            "lat": formatted_latitude,
            "lng": formatted_longitude,
            "tag": results[0]["detail_info"]["tag"]
        }
        print(address)

    with open("addressPositions.json", "w", encoding="utf-8") as file:
        json.dump(positionMap, file, ensure_ascii=False, indent=4)


cleanAddress()